package com.yiyihealth.cherriesadmin.controller;

import cn.hutool.core.util.StrUtil;
import com.yiyihealth.cherriesadmin.core.http.HttpResult;
import com.yiyihealth.cherriesadmin.core.web.BaseController;
import com.yiyihealth.cherriesadmin.core.webservice.MainServiceImplPortType;
import com.yiyihealth.cherriesadmin.core.webservice.MainServiceImplPortTypeService;
import com.yiyihealth.cherriesadmin.model.*;
import com.yiyihealth.cherriesadmin.model.jkt.JktFunc10002;
import com.yiyihealth.cherriesadmin.model.wrapper.PubDepartmentsWrapper;
import com.yiyihealth.cherriesadmin.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * 执行科室科室(PubDepartments)表控制层
 *
 * @author chen
 * @since 2020-09-14 20:03:49
 */
@Api(tags = "科室管理类")
@RestController
@RequestMapping("pubDepartments")
public class PubDepartmentsController extends BaseController<PubDepartments, PubDepartmentsWrapper, Long> {
    /**
     * 服务对象
     */
    @Resource
    private PubDepartmentsService pubDepartmentsService;
    @Resource
    private PubDoctorService pubDoctorService;
    @Resource
    private PubHospitalService hospitalService;
    @Resource
    private OrdSchedulingService schedulingService;
    @Resource
    private PubDictionaryService dictionaryService;

    @Autowired
    private RedisTemplate<Object, Object> redisCacheTemplate;

    @Override
    @InitBinder()
    public void initBinder(WebDataBinder binder) {
        super.setBaseService(pubDepartmentsService);
    }


    /**
     * 根据科室名称查询科室信息列表
     * @param depName
     * @param status
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "根据科室名称查询科室信息列表")
    @RequestMapping("/selectListByDepNameStatus")
    @ResponseBody
    public HttpResult selectListByDepNameStatus(@RequestParam String depName, @RequestParam String status) throws Exception {
        if (depName==null){
            depName="";
        }
        return HttpResult.success(pubDepartmentsService.selectListByDepNameStatus(depName,status));
    }

    /**
     * 根据上级科室ID 查询科室信息
     * @param depFatherId
     * @param hospitalId
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "根据上级科室ID 查询科室信息")
    @PostMapping("/selectListByDepFatherId")
    @ResponseBody
    public HttpResult selectListByDepFatherId(@RequestParam Long depFatherId,@RequestParam Long hospitalId) throws Exception {
        return HttpResult.success(pubDepartmentsService.selectListByDepFatherId(depFatherId,hospitalId));
    }


    @ApiOperation(value = "根据医院ID 查询医院信息")
    @RequestMapping("/selectListByHospitalId")
    @ResponseBody
    public HttpResult selectListByHospitalId(@RequestParam Long hospitalId) throws Exception {
        String status="0";
        return HttpResult.success(pubDepartmentsService.selectListByHospitalId(hospitalId,status));
    }
    @ApiOperation(value = "根据科室名称查询科室信息列表")
    @GetMapping("/selectListByDepNameStatus")
    @ResponseBody
    public HttpResult selectList(String depName,String status) {
        Map<String,Object> map = new HashMap<>();
        map.put("depName",depName);
        map.put("status",status);
        return HttpResult.success(pubDepartmentsService.selectList(map));
    }

    @ApiOperation(value = "H5根据科室名称查询科室信息列表")
    @RequestMapping("/selectListByDepFather")
    @ResponseBody
    public HttpResult selectListByDepFather(@RequestParam Long dicType,@RequestParam Long hospitalId) throws Exception {
        return HttpResult.success(pubDepartmentsService.selectListByDepFather(dicType,hospitalId));
    }


    @RequestMapping("/extractHisData")
    @ResponseBody
    public HttpResult extractHisData() throws Exception {
        try {
            pubDepartmentsService.ExtractHisData();
        }catch (Exception e){
            return HttpResult.failure(e.getMessage());
        }
        redisCacheTemplate.delete("options::0");
        redisCacheTemplate.delete("options::57170");
        redisCacheTemplate.delete("options::57171");
        redisCacheTemplate.delete("options::57172");
        schedulingService.selectListForOptions(0L);
        schedulingService.selectListForOptions(57170L);
        schedulingService.selectListForOptions(57171L);
        schedulingService.selectListForOptions(57172L);
        return HttpResult.success("");
    }

    @RequestMapping("/upload")
    @ResponseBody
    public HttpResult upload(@RequestParam Long hospitalId) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("depClinic","1");
        if (!hospitalId.toString().equals("0")){
            map.put("hospitalId",hospitalId);
        }

        MainServiceImplPortType service = new MainServiceImplPortTypeService().getMainServiceImplPortTypePort();
        List<PubDepartments> departmentsWrapperList = pubDepartmentsService.selectList(map);
        for (PubDepartments departments:departmentsWrapperList){
            if(!Optional.ofNullable(departments.getDepCode()).isPresent()){
                continue;
            }
            if (departments.getDepInternalCode().isEmpty()){
                throw new Exception(departments.getDepName()+"对应的标准科室编码不能为空!");
            }
            PubHospital hospital = hospitalService.selectByPrimaryKey(departments.getHospitalId());
            Document document = DocumentHelper.createDocument();
            Element root = document.addElement("data");
            Element funcode = root.addElement("funcode");
            funcode.setText("200102");
            //1. 医院编号 orgid 32 N 单医院接入传空，地 市平台接入传医院 在地市平台的编号
            Element orgid = root.addElement("orgid");
            orgid.setText(hospital.getHosMarkCode());

            //2. 科室编号 deptid 20 N 科室在医院内的唯 一标识
            Element deptid = root.addElement("deptid");
            deptid.setText(departments.getDepInternalCode());

            //3. 标准科室编号 stanid 20 N 见 S201-04 诊疗科 室编号
            Element stanid = root.addElement("stanid");
            PubDictionary dictionary = dictionaryService.selectByPrimaryKey(departments.getDepFatherId());
            if (Optional.ofNullable(dictionary).isPresent()){
                if (dictionary.getDicCode().equals("99")){
                    stanid.setText("50");
                    departments.setStatus("1");
                }
                stanid.setText(dictionary.getDicCode());
            }else {
                stanid.setText("50");
                departments.setStatus("1");
            }

            //4. 科室名称 deptname 40 N
            Element deptname = root.addElement("deptname");
            if (departments.getDepInternalCode().startsWith("H")){
                deptname.setText(departments.getDepName()+"(和平)");
            }else if (departments.getDepInternalCode().startsWith("D")){
                deptname.setText(departments.getDepName()+"(凤起)");
            }else {
                deptname.setText(departments.getDepName()+"(丰潭)");
            }
            //5. 科室介绍 description N
            Element description = root.addElement("description");
            description.setText(departments.getDescription()==null?"   ":departments.getDescription());

            //6. 最小年龄限制 age 2 N 科室接收患者最小 年龄， 0 为不限制
            Element age = root.addElement("age");
            age.setText("0");

            //7. 最大年龄限制 maxage 2 Y 科室接收患者最小 年龄， 0 为不限制
            Element maxage = root.addElement("maxage");
            maxage.setText("0");

            //8. 特色科室 specialty 1 Y 见特色专科
            Element specialty = root.addElement("specialty");
            specialty.setText("0");

            //9. 科室状态 state 1 Y 0-有效 1-无效
            Element state = root.addElement("state");
            if(StrUtil.isBlank(departments.getStatus())){
                departments.setStatus("1");
            }
            state.setText(departments.getStatus());

            String strResult = "";
            try {
                System.out.println(document.asXML());
                strResult = service.funMain(document.asXML());
                System.out.println(strResult);
                Document documentResult = DocumentHelper.parseText(strResult);
                //获取根节点
                Element rootElt = documentResult.getRootElement();
                //获取根节点名称
                String rootName = rootElt.getName();
                //获取子节点
                Element stateElt = rootElt.element("state");
                Element resultElt = rootElt.element("result");
                if (!stateElt.getTextTrim().equals("0")){
                    throw new Exception(resultElt.getTextTrim());
                }
            }catch (Exception e){
                throw new Exception("上传科室信息："+departments.getDepName()+e.getMessage());
            }
        }
        return HttpResult.success("上传科室信息成功！");
    }

    @ApiOperation(value ="根据科室下拉数据")
    @PostMapping("/selectOption")
    @ResponseBody
    public HttpResult selectOption(@RequestBody Map map){
        return HttpResult.success(pubDepartmentsService.selectOption(map));
    }

    @ApiOperation(value = "健康通--医院科室信息上传")
    @RequestMapping("/jktUpload")
    @ResponseBody
    public HttpResult jktUpload(@RequestParam Long hospitalId) throws Exception {
        try {
            pubDepartmentsService.jktUpload(hospitalId);
        }catch (Exception e){
            return HttpResult.failure(e.getMessage());
        }
        return HttpResult.success("健康通科室信息上传成功！");
    }
}
